import 'dart:convert';
import 'dart:math';

import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_shark_im/entity/message/base_message_entity.dart';
import 'package:flutter_shark_im/page/home_page.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import 'page/login_page.dart';

void main() => runApp(SharkIm());

class SharkIm extends StatelessWidget {
  // 登陆用户id
  static String id;
  // 聊天记录
  static Map<String, List<Message>> chatMessage;

  static const address = 'ws://www.xyzt8.top:8123/ws';

  static int no = 0;

  static String name = nameList[new Random().nextInt(nameList.length)];

  static int avatar = new Random().nextInt(10);

  IOWebSocketChannel channel;

  final eventBus = EventBus();
  
  static List<Message> getMessageList(String id, int pageNo, int pageSize) {
    if (chatMessage[id] == null) {
      chatMessage[id] = <Message>[];
    }
    final list = chatMessage[id];
    // TODO mock message
    list.clear();
    DateTime begin = DateTime.now();
    for(int i=0; i<100; i++) {
      begin = begin.add(Duration(minutes: Random().nextInt(10)));
      list.add(Message(isMe: i.isOdd, content: '$begin~', time: begin));
    }
    list.sort((a, b) => a.time.compareTo(b.time));
    ////////////////////////
    if (pageSize >= list.length) {
      return list;
    }  else {
      return list.sublist(list.length - pageSize);
    }
  }

  static addMessage(String content, String id) {
    if (chatMessage[id] == null) {
      chatMessage[id] = [];
    }
    final list = chatMessage[id];
    list.add(Message(isMe: false, content: content, time: DateTime.now()));
  }

  _onData(data) {
    var obj = json.decode(data);
    var msg = BaseMessageEntity.convertEntity(obj);
    eventBus.fire(msg);
  }

  _onError(err) {
    debugPrint(err.runtimeType.toString());
    WebSocketChannelException ex = err;
    debugPrint(ex.message);
  }

  _onDone() {
    debugPrint("Socket is closed");
    channel = IOWebSocketChannel.connect(address);
  }

  _init() {
    if (channel == null) {
      channel  = IOWebSocketChannel.connect(address);
      channel.stream.listen(this._onData, onError: _onError, onDone: _onDone);
    }
    if (chatMessage == null) {
      chatMessage = new Map();
    }
  }

  @override
  Widget build(BuildContext context) {
    _init();
    // 监听
    eventBus.on<Map<String, dynamic>>().listen((data) {
      data['no'] = SharkIm.no++;
      data['createTime'] = DateTime.now().toString().split('.')[0].toString();
      channel.sink.add(json.encode(data));
    });
    return MaterialApp(
      title: 'Shark-im',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ApplicationPage(eventBus, channel ),
      routes: <String, WidgetBuilder> {
        '/home': (_) => new Home(eventBus: eventBus)
      },
    );
  }
}

class ApplicationPage extends StatefulWidget {

  final String title = '登陆';

  final EventBus eventBus;

  final IOWebSocketChannel channel;

  @override
  LoginPageState createState() => LoginPageState();

  ApplicationPage(this.eventBus, this.channel);

}

const nameList = ["曹操", "刘备", "孙权", "关羽", "张飞", "诸葛亮", "赵云", "黄忠", "马超", "魏延", "法正", "庞统", "周瑜", "司马懿", "徐庶", "曹丕", "曹植", "曹彰", "郭嘉", "荀彧", "荀攸", "贾诩", "程昱", "满宠", "蒋济", "韩浩", "陈群", "张辽", "徐晃", "许褚", "典韦", "张郃", "于禁", "乐进", "李典", "曹仁", "文聘", "张燕", "曹洪", "曹休", "曹真", "夏侯敦", "夏侯渊", "夏侯霸", "夏侯威", "姜维", "鲁肃", "吕蒙", "陆逊", "张昭", "张纮", "虞翻", "丁奉", "徐盛", "陈武", "潘璋", "甘宁", "太史慈", "蒋钦", "周泰", "董袭", "骆统", "廖化", "马谡", "王平", "蒋琬", "刘禅", "孙亮", "凌统", "费祎", "诸葛瑾", "公孙渊", "邓艾", "钟会", "诸葛恪", "司马师", "司马昭", "孙皓", "曹髦"];